<template>
  <van-form @submit="check">
    <van-field
      v-model="business.email"
      name="email"
      label="邮箱"
      placeholder="请输入邮箱"
      readonly
      :rules="[
        { required: true, message: '请输入邮箱' },
        {
          pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
          message: '邮箱格式不正确',
        },
      ]"
    />

    <van-field
      v-model="vercode"
      name="vercode"
      center
      clearable
      label="邮箱验证码"
      placeholder="请输入邮箱验证码"
      :rules="[{ required: true, message: '请输入邮箱验证码' }]"
    >
      <template #button>
        <van-button
          size="small"
          type="primary"
          @click="send"
          :disabled="disabled"
          >{{ msg }}</van-button
        >
      </template>
    </van-field>

    <div style="width: 50%; margin: 2em auto">
      <van-button round block type="primary" native-type="submit">
        提交
      </van-button>
    </div>
  </van-form>
</template>

<script setup>
// this代理
const { proxy } = getCurrentInstance();

const business = proxy.$business;
const vercode = ref("");
const msg = ref("发送验证码");
const disabled = ref(false);

// 挂载前钩子
onBeforeMount(() => {
  send(false);
});

//邮箱发送
const send = async (bool) => {
  // 组装参数
  let params = {
    busid: business.value.id,
    // email: business.value.email,
  };
  if (bool !== false) {
    params.email = business.value.email;
  }
  // 发起请求
  let result = await proxy.$http.post({
    url: "/business/send",
    params,
  });
  // 处理请求结果
  if (result.code === 1) {
    proxy.$success(result.msg);
    // 页面响应式数据：倒计时
    msg.value = "正在发送中.....";
    disabled.value = true;
    msg.value = 60;

    let T = setInterval(() => {
      if (msg.value <= 0) {
        //停止定时器
        clearInterval(T);
        msg.value = "重新发送验证码";
        disabled.value = false;
      } else {
        msg.value--;
      }
    }, 1000);
  } else {
    if (result.data.action === "auth") {
      return;
    }
    proxy.$fail({
      message: result.msg,
      onClose: () => {
        proxy.$router.go(-1);
      },
    });
  }
};

//邮箱验证
const check = async (values) => {
  // 组装参数
  let params = {
    code: vercode.value,
    email: business.value.email,
    busid: business.value.id,
  };
  // 发起请求
  let result = await proxy.$http.post({
    url: "/business/EmsCheck",
    params,
  });
  if (result.code === 1) {
    proxy.$success({
      message: result.msg,
      onClose: () => {
        proxy.$router.go(-1);
      },
    });
  } else {
    proxy.$fail(result.msg);
    // proxy.$fail({
    //   message: result.msg,
    //   onClose: () => {
    //     proxy.$router.go(-1);
    //   },
    // });
  }
};
</script>